import { globalError } from '../interceptors/httpResult.interceptor';
import { createParamDecorator } from '@nestjs/common';
import * as express from 'express';

/**
 * 对请求参数进行验证
 * NOTE:get请求只查看query中的参数。其它请求方式只查看body中的参数
 * 支持传string、array、object，报错时只显示缺失key
 * 传object的例子是：{user:'用户'},其中key用来校验，value用来报错
 * string会用空格进行split，转化为array
 */
export const Valid = createParamDecorator(
    async (data, req: express.Request) => {
        if (data) {
            let requiredParams: string[]; // 必填字段
            let requestParams: string[]; //请求字段
            let method = req.method.toLowerCase(); //请求方式
            let trans = false; //objectmo
            if (method == 'get') {
                requestParams = Object.keys(req.query);
            } else {
                requestParams = Object.keys(req.body);
            }
            if (typeof data == 'object') {
                requiredParams = Object.keys(data);
            } else if (Array.isArray(data)) {
                requiredParams = data;
            } else if (typeof data == 'string') {
                requiredParams = data.split(' ');
            }
            let missParams = checkParams({
                requiredParams,
                requestParams,
            });
            if (trans) {
                missParams = missParams.map(mp => data[mp]);
            }
            if (missParams.length) {
                globalError(
                    `请求参数：${missParams.join(
                        '、',
                    )}字段不存在或格式不正确。`,
                );
            }
        }
        return true;
    },
);

/**
 * 检查必填项
 * @param requiredParams 必填项
 * @param requestParams 请求中的参数
 * @returns missParams 缺失项
 */
const checkParams = (opts: {
    requiredParams: string[];
    requestParams: string[];
}): string[] => {
    let { requiredParams, requestParams } = opts;
    return requiredParams.filter(p => {
        return !requestParams.includes(p);
    });
};
